package com.example.journalegocentrique;

import java.io.File;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;


public class OrientationPicture {

	public static Bitmap changeOrientation(String mCurrentPhotoPath) throws IOException {
		File f=new File(mCurrentPhotoPath);
		// il file potrebbe essere stato cancellato dalla galleria
		if(f.exists()){
			BitmapFactory.Options bfOptions = new BitmapFactory.Options();
			Bitmap image = null;
			Bitmap defImage = null;
			bfOptions.inDither = false;
			bfOptions.inPurgeable = true;
			bfOptions.inInputShareable = true;
			bfOptions.inSampleSize = 2;
			bfOptions.inTempStorage=new byte[32 * 1024]; 
			image = BitmapFactory.decodeFile(mCurrentPhotoPath, bfOptions);
			ExifInterface exif = null;
			exif = new ExifInterface(mCurrentPhotoPath);
			int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			Matrix mat = new Matrix();
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_270:
				mat.postRotate(270);
				defImage = Bitmap.createBitmap(image, 0, 0,
						image.getWidth(), image.getHeight(), mat, true);
				return defImage;
			case ExifInterface.ORIENTATION_ROTATE_180:
				mat.postRotate(180);
				defImage = Bitmap.createBitmap(image, 0, 0,
						image.getWidth(), image.getHeight(), mat, true);
				return defImage;
			case ExifInterface.ORIENTATION_ROTATE_90:
				mat.postRotate(90);
				defImage = Bitmap.createBitmap(image, 0, 0,
						image.getWidth(), image.getHeight(), mat, true);
				return defImage;
			case ExifInterface.ORIENTATION_NORMAL:
				mat.postRotate(0);
				defImage = Bitmap.createBitmap(image, 0, 0,
						image.getWidth(), image.getHeight(), mat, true);
				return defImage;
			case ExifInterface.ORIENTATION_UNDEFINED:
				mat.postRotate(0);
				defImage = Bitmap.createBitmap(image, 0, 0,
						image.getWidth(), image.getHeight(), mat, true);
				return defImage;	
			default: return null;
			}
		}
		else return null;
	}

}
